package com.example.prison.protocol;

import com.example.prison.entity.AreaManagement;
import com.example.prison.util.Crc16Util;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;

import static com.example.prison.protocol.StringUtil.byteToPrintAsciiHexString;

@Slf4j
public class QueryDevice {

    public AreaManagement QueryDeviceType() throws IOException {
        Socket socket = new Socket("192.168.4.101", 8886);
        log.info("连接成功");
        OutputStream outputStream = socket.getOutputStream();//获取一个输出流，向服务端发送信息
        //        byte[] sendInfo = new byte[] { 0x00,0x00,0x00,0x00,0x00,0x06,0x01,0x03,0x00, 0x64, 0x00, 0x01 };  //发送给Modbus软件的消息
        byte[] sendInfo = new byte[]{0x01, 0x03, 0x0003, 0x0001};  //发送的消息  查询设备类型
        byte[] crc = Crc16Util.getCrc16(sendInfo);
        System.out.println(Arrays.toString(crc));
        log.info("查询设备类型");
        outputStream.write(sendInfo);//往服务端写数据
        outputStream.flush();
        log.info("等待服务端响应");
        InputStream inputStream = socket.getInputStream();//获取一个输入流，接收服务端的信息
        byte[] bs = new byte[32];
        inputStream.read(bs);
        System.out.println(Arrays.toString(bs));
        String res1 = byteToPrintAsciiHexString(bs);  //输出十六进制，调用刚刚的转换函数
        System.out.println(res1);
        log.info("释放资源");
        socket.shutdownOutput();//关闭输出流
        inputStream.close();
        outputStream.close();

        socket.close();

        AreaManagement area = decord(res1);
        return area;
    }

    public AreaManagement QueryDeviceStatus() throws IOException {

        Socket socket = new Socket("192.168.4.101", 8886);
        log.info("连接成功");
        OutputStream outputStream = socket.getOutputStream();
        //        byte[] sendInfo = new byte[] { 0x00,0x00,0x00,0x00,0x00,0x06,0x01,0x03,0x00, 0x64, 0x00, 0x01 };  //发送给Modbus软件的消息
        byte[] sendInfo = new byte[]{0x01, 0x03, 0x0001, 0x0007};  //发送的消息  查询设备状态
        byte[] crc = Crc16Util.getCrc16(sendInfo);
        System.out.println(Arrays.toString(crc));
        log.info("查询设备状态");
        outputStream.write(sendInfo);
        outputStream.flush();
        log.info("等待服务端响应");
        InputStream inputStream = socket.getInputStream();
        byte[] bs = new byte[32];
        inputStream.read(bs);

        int str = inputStream.read(bs);
        String res1 = byteToPrintAsciiHexString(bs);  //输出
        System.out.println(str);

        log.info("释放资源");
        socket.shutdownOutput();
        inputStream.close();
        outputStream.close();

        socket.close();

        AreaManagement area = decord(res1);
        return area;
    }

    public static AreaManagement decord(String str) {


        AreaManagement area = new AreaManagement();
        return area;
    }

}
